<template>
    <div>
        <el-button @click="dialogVisible = true">发布签到</el-button>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="180">
            </el-table-column>
            <el-table-column prop="logo" label="签到名称" width="180">
            </el-table-column>
            <el-table-column label="签到班级">
                <template slot-scope="scope">
                    {{classes.find(item=>item.id === scope.row.classId).className}}
                </template>
            </el-table-column>
            <el-table-column label="创建时间">
                <template slot-scope="scope">
                    {{scope.row.createdTime.replace("T"," ")}}
                </template>
            </el-table-column>
            <el-table-column label="结束时间">
                <template slot-scope="scope">
                    {{scope.row.endTime.replace("T"," ")}}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="downloadExcel(scope.row.id,scope.row.classId,scope.row.logo)">下载签到表</el-button>
                </template>
            </el-table-column>
        </el-table>



        <el-dialog title="发布签到" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-input placeholder="请输入签到名称" v-model="prams.logo">
                <template slot="prepend">签到名称</template>
            </el-input>
            <span>结束时间：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <el-time-picker v-model="prams.time" :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }" placeholder="请选择结束时间">
            </el-time-picker><br>

            <span>请选择班级：&nbsp;</span>
            <el-select v-model="prams.classes" multiple placeholder="请选择班级">
                <el-option v-for="item in classes" :key="item.id" :label="item.className" :value="item.id">
                </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose()">取 消</el-button>
                <el-button type="primary" @click="submisslogo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<style lang="less" scoped>
    .el-input {
        margin-bottom: 10px;
    }

    .el-table {
        margin-top: 20px;
    }
</style>


<script>
    import axios from "axios";
    export default {
        created() {
            this.getCalssList()
            this.getLogoList()
        },
        data() {
            return {
                tableData: null,// 表格数据
                dialogVisible: false,
                classes: null,
                prams: {
                    logo: null,
                    classes: null,
                    time: new Date() // 结束时间
                }
            }
        },
        methods: {
            handleClose() {
                this.dialogVisible = false
                this.prams = {
                    logo: null,
                    classes: null,
                    time: null,
                }
                this.getLogoList()
            },
            // 获取班级信息
            async getCalssList() {
                const { data: res } = await this.$axios.get("/getClasses")
                this.classes = res.data
            },
            // 提交签到
            async submisslogo() {
                if (this.prams.logo === null) {
                    return this.$message("请完善表格")
                }
                if (this.prams.time === null) {
                    return this.$message("请完善表格时间")
                }
                if (this.prams.classes === null || this.prams.classes.length === 0) {
                    return this.$message("请输入班级")
                }
                this.prams.time = this.formatDate(this.prams.time)
                const { data: res } = await this.$axios.post("/sublogo", this.prams)
                if (res.code === 200) {
                    this.handleClose()
                    return this.$message.success("发布成功")
                }
                if (res.code === 201) {
                    return this.$message.error("请完善表格")
                }
                if (res.code === 701) {
                    return this.$message.error("请完善表格中的结束时间")
                }
                if (res.code === 202) {
                    return this.$message.error("签到名称重复")
                }
                if (res.code === 203) {
                    return this.$message.error("签到班级在3小时以内重复")
                }
                return this.$message.error("网络错误")
            },

            // 获取签到信息
            async getLogoList() {
                const { data: res } = await this.$axios.get("/getLogoList")
                this.tableData = res.data
            },

            // 时间格式转化
            formatDate(date) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1  
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');

                // 注意：这里返回的是本地时间的字符串，不是UTC时间的字符串  
                return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
            },

            // 签到表下载
            async downloadExcel(id,classId,logo) {
                try {
                    const params = {
                        id: id
                    };
                    // 设置文件下载明
                    let fileName = this.classes.find(item=>item.id === classId).className + logo + ".xlsx";

                    const response = await axios({
                        method: 'get',
                        url: 'http://127.0.0.1:8000/teacher/getLogoScore',
                        responseType: 'arraybuffer', // 或者 'arraybuffer'  
                        params: params
                    });
                    if (response.status === 200) {
                        const url = window.URL.createObjectURL(new Blob([response.data]));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', fileName); // 设置下载文件的名称  
                        document.body.appendChild(link);
                        link.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(link);
                    } else {
                        this.$message.error("获取失败")
                        console.error('请求失败', response);
                    }
                } catch (error) {
                    console.error('请求出错', error);
                }
            },

        }
    }
</script>